package com.vancouver.knows.ui.activity.event;

import java.net.URLEncoder;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;

import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.pangu.service.ActionException;
import com.pangu.task.IResultReceiver;
import com.pangu.task.mark.ATaskMark;
import com.pangu.ui.refresh.ARefreshViewController;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.MainApplication.TrackerName;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.ui.fragment.event.EventPullDetailControllerView;
import com.vancouver.knows.ui.view.RichWebView;
import com.vancouver.knows.util.AnalyticsConstants;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.util.CircleTransform;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.EventDetailInfo;
import com.vancouver.knows.business.bean.UserInfo;
import com.vancouver.knows.business.task.mark.FetchEventDetailTaskMark;
import com.vancouver.knows.business.task.mark.UserDeleteFollowTaskMark;
import com.vancouver.knows.business.task.mark.UserFollowTaskMark;

public class EventDetailActivity extends BaseActivity implements IResultReceiver {

	@Bind(R.id.title)
	TextView title;
	@Bind(R.id.location)
	TextView location;
	@Bind(R.id.timeDescription)
	TextView timeDescription;
	@Bind(R.id.admission)
	TextView admission;
	@Bind(R.id.followTitle)
	TextView followTitle;
	@Bind(R.id.followInfo)
	TextView followInfo;
	@Bind(R.id.userFollowedLayout)
	LinearLayout userFollowedLayout;
	@Bind(R.id.content)
	RichWebView content;
	@Bind(R.id.detailContentLayout)
	LinearLayout detailContentLayout;
	@Bind(R.id.loadingView)
	View loadingView;
	@Bind(R.id.mainContent)
	EventPullDetailControllerView mainContent;
	@Bind(R.id.follow)
	TextView follow;
	@Bind(R.id.toolbar)
	Toolbar toolbar;

	private BusinessModule bModule;
	private EventDetailInfo eventDetailInfo;
	private String postId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_event_detail);
		bModule = imContext.getBusinessModule();

		Intent intent = getIntent();
		if (intent == null) {
			return;
		}

		String deepLink = intent.getDataString();
		if (intent.getDataString() != null) {
			postId = deepLink.substring(deepLink.lastIndexOf("/") + 1);
			if (StringUtil.isEmptyString(postId)) {
				return;
			}

			int indexOfChar = postId.indexOf("?");
			if (indexOfChar != -1) {
				postId = postId.substring(0, indexOfChar);
			}
		} else {
			postId = intent.getStringExtra("postId");
			if (StringUtil.isEmptyString(postId)) {
				return;
			}
		}


		toolbar.setTitle("");
		setSupportActionBar(toolbar);
		toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back));

		loadingView.setVisibility(View.VISIBLE);
		detailContentLayout.setVisibility(View.GONE);
		ATaskMark aTaskMark = bModule.getTaskMarkPool().getFetchEventDetailTaskMark(postId);
		mainContent.init(postId, aTaskMark, this);

		updateEventDetailInfo();
		if (eventDetailInfo == null) {
			mainContent.loadData();
		} else {
			init();
		}
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	private void init() {
		loadingView.setVisibility(View.GONE);
		detailContentLayout.setVisibility(View.VISIBLE);

		title.setText(eventDetailInfo.getTitle());
		String lookLoaction = getString(R.string.look_location);
		String locationStr = eventDetailInfo.getVenue() + "  " + lookLoaction;
		location.setText(AppUtils.replaceColor(locationStr, lookLoaction, getResources().getColor(R.color.orange)));
		timeDescription.setText(eventDetailInfo.getTimeDescription());
		admission.setText(eventDetailInfo.getAdmission());
		followTitle.setText(AppUtils.getArrayStr(eventDetailInfo.getCategory()));

		String contentStr = eventDetailInfo.getContent();
		content.loadHtmlText(contentStr);
		follow.setTextColor("Y".equals(eventDetailInfo.getUserFollowed()) ? getResources().getColor(R.color.orange)
				: getResources().getColor(R.color.common_font));
		if ("Y".equals(eventDetailInfo.getUserFollowed())) {
			Drawable drawable = getResources().getDrawable(R.drawable.event_follow_active);
			drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
			follow.setCompoundDrawables(drawable, null, null, null);
		} else {
			Drawable drawable = getResources().getDrawable(R.drawable.event_follow);
			drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
			follow.setCompoundDrawables(drawable, null, null, null);
		}

		updateFollowLayout();
	}

	public void updateEventDetailInfo() {
		eventDetailInfo = bModule.getCacheManager().getEventDetailInfoMap().get(postId);
	}

	private void updateFollowLayout() {
		followInfo.setText(getString(R.string.followed, eventDetailInfo.getFollowCount()));
		int count = userFollowedLayout.getChildCount();
		int userFollowedCount = eventDetailInfo.getEventDetailUserInfoList().size();
		for (int i = 0; i < count; i++) {
			ImageView imgView = (ImageView) userFollowedLayout.getChildAt(i);
			if (i >= userFollowedCount) {
				imgView.setVisibility(View.GONE);

			} else {
				imgView.setVisibility(View.VISIBLE);
				String img = eventDetailInfo.getEventDetailUserInfoList().get(i).getAvatar();
				if (!StringUtil.isEmptyString(img)) {
					Picasso.with(imContext).load(img).transform(new CircleTransform()).centerCrop()
							.resizeDimen(R.dimen.detail_user_followed_size, R.dimen.detail_user_followed_size)
							.into(imgView);
				} else {
					imgView.setImageResource(R.drawable.me_icon_login);
				}
			}
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@OnClick(R.id.officialWebsite)
	public void onOfficialWebsiteClick() {
		AppUtils.showBrower(this, eventDetailInfo.getWebsite());
	}

	@OnClick(R.id.recommend)
	public void onRecommendClick() {
		Tracker t = ((MainApplication) getApplication()).getTracker(TrackerName.APP_TRACKER);
		t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_EVENT_DETAIL);
		t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_BTN)
				.setAction(AnalyticsConstants.ACTION_ONCLICK).setLabel(AnalyticsConstants.LABEL_EVENT_DETAIL_SHARE)
				.build());

		AppUtils.shareContent(this, eventDetailInfo.getTitle(), eventDetailInfo.getPermalink(),
				eventDetailInfo.getAttachmentImage());
	}

	@OnClick(R.id.follow)
	public void OnFollowClick() {
		Tracker t = ((MainApplication) getApplication()).getTracker(TrackerName.APP_TRACKER);
		t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_EVENT_DETAIL);
		t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_BTN)
				.setAction(AnalyticsConstants.ACTION_ONCLICK).setLabel(AnalyticsConstants.LABEL_EVENT_DETAIL_FOLLOW)
				.build());

		if (!AppUtils.getLoginStatus(this)) {
			return;
		}

		UserInfo userInfo = bModule.getCacheManager().getUserInfo();

		if ("Y".equals(eventDetailInfo.getUserFollowed())) {
			UserDeleteFollowTaskMark taskMark = bModule.getTaskMarkPool().getUserDeleteFollowTaskMark(
					eventDetailInfo.getId());
			bModule.getServiceWrapper().userDeleteFollow(this, taskMark, eventDetailInfo.getId(), userInfo.getUserID());

		} else {
			UserFollowTaskMark taskMark = bModule.getTaskMarkPool().getUserFollowTaskMark(eventDetailInfo.getId());
			bModule.getServiceWrapper().userFollow(this, taskMark, eventDetailInfo.getId(), userInfo.getUserID());
		}
	}

	@OnClick(R.id.location)
	public void onLocationClick() {
		try {
			String loaction = "geo:0,0?q=" + URLEncoder.encode(eventDetailInfo.getLocation());
			Uri gmmIntentUri = Uri.parse(loaction);
			Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
			mapIntent.setPackage("com.google.android.apps.maps");
			startActivity(mapIntent);

		} catch (Exception e) {
			Toast.makeText(this, R.string.no_googglemap, 200).show();
		}
	}

	@Override
	public void receiveResult(ATaskMark taskMark, ActionException exception, Object trackerResult) {
		if (taskMark instanceof FetchEventDetailTaskMark) {
			updateEventDetailInfo();
			if (taskMark.getTaskType() == ATaskMark.TYPE_REFRESH) {
				if (taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
					mainContent.refreshFinish(ARefreshViewController.SUCCEED);

				} else {
					mainContent.refreshFinish(ARefreshViewController.FAIL);
				}
			}

			if (taskMark.getTaskStatus() == ATaskMark.HANDLE_ERROR) {
				Toast.makeText(this, R.string.load_error, 200).show();
				finish();

			} else if (taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
				init();
			}

		} else if ((taskMark instanceof UserFollowTaskMark || taskMark instanceof UserDeleteFollowTaskMark)
				&& taskMark.getTaskStatus() == ATaskMark.HANDLE_OVER) {
			follow.setTextColor("Y".equals(eventDetailInfo.getUserFollowed()) ? getResources().getColor(R.color.orange)
					: getResources().getColor(R.color.common_font));
			if ("Y".equals(eventDetailInfo.getUserFollowed())) {
				Drawable drawable = getResources().getDrawable(R.drawable.event_follow_active);
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
				follow.setCompoundDrawables(drawable, null, null, null);
			} else {
				Drawable drawable = getResources().getDrawable(R.drawable.event_follow);
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
				follow.setCompoundDrawables(drawable, null, null, null);
			}
			updateFollowLayout();

		}
	}
}
